/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain.shell;

import tal.drivechain.chain.AbortChainException;
import tal.drivechain.chain.script.ScriptCommand;
import tal.drivechain.chain.script.ScriptCompiler;
import tal.drivechain.parsing.ParsingAid;
import tal.drivechain.plugin.Module;

/**
 *
 * @author eisental
 */
public class ModuleObject extends ShellObject {

    public ModuleObject(DriveShell shell) {
        super("module", "modules", "mod", shell);
    }

    @Override
    public boolean isActionSupported(Action action) {
        return (action==Action.make);
    }

    @Override
    public void make(String command) throws IllegalArgumentException {
        int spaceIdx = command.indexOf(" ");
        if (spaceIdx==-1 || ParsingAid.isNested(command, spaceIdx, "{", "}"))
            throw new IllegalArgumentException("Invalid syntax (should be create module <instance name> <module type> { <properties> } ");

        String instanceName = command.substring(0, spaceIdx);
        String moduleDef = command.substring(spaceIdx+1);
        ScriptCommand moduleCommand = new ScriptCommand("module", instanceName, moduleDef);
        Module module = null;
        try {
            module = ScriptCompiler.parseModuleCommand(shell.getActiveChain(), moduleCommand);
            module.setupProperties();
            module.getParentChain().dispatchNodeConfigured(module);
            out.println("Added module " + module.getName() + " (" + module.getNodeClassName() + ") to " + shell.getActiveChain().getName());
            if (shell.getActiveChain().isRunning()) module.start();
        } catch (AbortChainException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
    }

    @Override
    public void set(String command) throws IllegalArgumentException {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public void list() throws IllegalArgumentException {
        out.println(InfoPrinter.printModules(shell.getActiveChain()));
    }

    @Override
    public void inspect(String command) throws IllegalArgumentException {
    }

    @Override
    public void remove(String command) throws IllegalArgumentException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}
